import {Text, View} from "@tarojs/components";
import {Button, Cell, Empty, Search} from "@antmjs/vantui";
import Utils from "@/utils/common";
import React, {useCallback, useRef, useState} from "react";
import {TeamModel} from "@/common/apis/model";
import {teamRelationSaveApi, teamSearchListApi} from "@/common/apis/home_datasource";
import LocalUtils from "@/utils/local_utils";


definePageConfig({
  navigationBarTitleText: '添加课题组'
})

export default function SearchTeam() {

  const [items, setItems] = useState<TeamModel[]>()

  const inputKey = useRef('');

  const searchAction = useCallback((e) => {
    if (!Utils.isNotBlank(e.detail)) {
      Utils.showErrorToast('请输入课题组名字')
      return;
    }
    if (e.detail === inputKey.current) {
      return;
    }
    inputKey.current = e.detail;
    teamSearchListApi(inputKey.current).then((res) => {
      if (res) {
        setItems(res)
      }

    })
  }, []);


  return (
    <View style={{display: 'flex', flexDirection: 'column', height: '100vh'}}>
      <View>
        <Search
          placeholder='请输入课题组名字'
          onSearch={searchAction}
        />
      </View>
      <View style={{flex: 1}}>
        {
          items && !Utils.isEmpty(items) ? items.map((item, i) => {
            return <Cell key={item.id}
                         renderTitle={<Text style={{fontSize: '16px'}}>{item.name}</Text>}
            >
              <Button style={{marginLeft: '10px'}} size='normal' type='info' hairline plain onClick={() => {
                teamRelationSaveApi(item.id, LocalUtils.getUserId()).then((res) => {
                  if (res) {
                    Utils.showErrorToast('申请成功，请等待审核')
                  }
                })
              }}
              >
                申请
              </Button>
            </Cell>
          }) : <Empty description='暂无数据'/>
        }
      </View>
    </View>
  )
}

